import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Row, Col, Card, Button, InputNumber, Typography, Divider, message, Image } from 'antd';
import { ShoppingCartOutlined, HeartOutlined } from '@ant-design/icons';
import { Product, CartItem } from '../../types';
import { mockProducts } from '../../services/mockData';
import { Storage, STORAGE_KEYS } from '../../utils/storage';

const { Title, Text, Paragraph } = Typography;

const ProductDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [product, setProduct] = useState<Product | null>(null);
  const [quantity, setQuantity] = useState(1);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    if (id) {
      const found = mockProducts.find(p => p.id === id);
      setProduct(found || null);
    }
  }, [id]);

  const handleAddToCart = () => {
    if (!product) return;
    
    setLoading(true);
    setTimeout(() => {
      const cartItems = Storage.get<CartItem[]>(STORAGE_KEYS.CART) || [];
      const existingItem = cartItems.find(item => item.productId === product.id);
      
      if (existingItem) {
        existingItem.quantity += quantity;
      } else {
        const newItem: CartItem = {
          id: Date.now().toString(),
          productId: product.id,
          product,
          quantity,
          selected: true
        };
        cartItems.push(newItem);
      }
      
      Storage.set(STORAGE_KEYS.CART, cartItems);
      setLoading(false);
      message.success('已添加到购物车');
    }, 500);
  };

  const handleBuyNow = () => {
    if (!product) return;
    
    const cartItem: CartItem = {
      id: Date.now().toString(),
      productId: product.id,
      product,
      quantity,
      selected: true
    };
    
    navigate('/order/create', { state: { cartItems: [cartItem] } });
  };

  if (!product) {
    return <div style={{ textAlign: 'center', padding: '50px 0' }}>商品不存在</div>;
  }

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      <Row gutter={24}>
        {/* 商品图片 */}
        <Col xs={24} md={12}>
          <Card>
            <Image
              src={product.image}
              alt={product.name}
              style={{ width: '100%', maxHeight: 400, objectFit: 'cover' }}
            />
          </Card>
        </Col>

        {/* 商品信息 */}
        <Col xs={24} md={12}>
          <Card>
            <Title level={2}>{product.name}</Title>
            
            <div style={{ margin: '20px 0' }}>
              <span className="price-current" style={{ fontSize: 24 }}>
                ¥{product.price}
              </span>
              {product.originalPrice && (
                <span className="price-original" style={{ fontSize: 16, marginLeft: 12 }}>
                  ¥{product.originalPrice}
                </span>
              )}
            </div>

            <Divider />

            <div style={{ margin: '16px 0' }}>
              <Text strong>销量：</Text>
              <Text>{product.sales}</Text>
            </div>

            <div style={{ margin: '16px 0' }}>
              <Text strong>库存：</Text>
              <Text>{product.stock} 件</Text>
            </div>

            <div style={{ margin: '24px 0' }}>
              <Text strong style={{ marginRight: 16 }}>数量：</Text>
              <InputNumber
                min={1}
                max={product.stock}
                value={quantity}
                onChange={(value) => setQuantity(value || 1)}
              />
            </div>

            <div style={{ margin: '32px 0' }}>
              <Button
                type="primary"
                size="large"
                icon={<ShoppingCartOutlined />}
                onClick={handleAddToCart}
                loading={loading}
                style={{ marginRight: 16 }}
              >
                加入购物车
              </Button>
              <Button
                type="primary"
                size="large"
                danger
                onClick={handleBuyNow}
              >
                立即购买
              </Button>
            </div>

            <Button
              type="text"
              icon={<HeartOutlined />}
              style={{ color: '#999' }}
            >
              收藏商品
            </Button>
          </Card>
        </Col>
      </Row>

      {/* 商品详情 */}
      <Row style={{ marginTop: 24 }}>
        <Col span={24}>
          <Card title="商品详情">
            <Paragraph>
              {product.description}
            </Paragraph>
            <div style={{ textAlign: 'center', margin: '40px 0' }}>
              <Text type="secondary">更多商品详情图片...</Text>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default ProductDetail;
